﻿
    var mapAddressDirective = function ($compile) {
        return {
            restrict: 'AE',
            link: function (scope, element, attrs) {
                var mapAddressId = attrs.mapAddressId;

                var lat = attrs.lat;
                var lng = attrs.lng;

                var placeholder = attrs.placeholder;


                scope[mapAddressId] = scope[mapAddressId] ||
                    {
                        defaultLocation: { lat: lat, lng:lng}
                    };

                var template = '<input type="text" style="' + attrs.style + '" placeholder="' + placeholder + '" ng-model="' + mapAddressId + '.findText" ng-change="' + mapAddressId + '.findTextChange()" />';

                if (mapAddressId) {
                    scope[mapAddressId].location = scope[mapAddressId].location || { lat: scope[mapAddressId].defaultLocation.lat, lng: scope[mapAddressId].defaultLocation.lng };

                    scope[mapAddressId].findTextChange = function () {
                        if (!scope[mapAddressId].findText.length)
                        {
                            scope[mapAddressId].location.lat = scope[mapAddressId].defaultLocation.lat;
                            scope[mapAddressId].location.lng = scope[mapAddressId].defaultLocation.lng;
                            return;
                        }
                        var geocoder = new google.maps.Geocoder();
                        geocoder.geocode({ 'address': scope[mapAddressId].findText }, function (results, status) {
                            if (status == google.maps.GeocoderStatus.OK) {
                                scope[mapAddressId].location.lat = results[0].geometry.location.lat();
                                scope[mapAddressId].location.lng = results[0].geometry.location.lng();

                                // its async call!!!!!!
                                scope.$apply();
                            }
                        });
                    }

                    element.html('').append($compile(template)(scope));
                }
            }
        };
    }
